<template>
  <div id="discount_coupon_list">
    <div class="search-box">
      <Row type="flex">
        <Row type="flex" justify="start" class="search-item-left">
          <Col class="search-item">
            <span class="search-label">状态:</span>
            <Select v-model="searchObj.status" @on-change="search" style="width:180px">
              <Option :value="-1">全部</Option>
              <Option :value="1">启用</Option>
              <Option :value="0">未启用</Option>
            </Select>
          </Col>
          <Col class="search-item">
            <span class="search-label">类型:</span>
            <Select v-model="searchObj.templateType" @on-change="search" style="width:180px">
              <Option :value="-1">全部</Option>
              <Option v-for="(item, index) in templateTypeList" :value="item.value" :key="index">{{item.label}}</Option>
            </Select>
          </Col>
          <Col class="search-item">
            <span class="search-label">适用产品:</span>
            <Select v-model="searchObj.suitableType" @on-change="search" style="width:180px">
              <Option :value="-1">全部</Option>
              <Option v-for="(item, index) in messageActivityList" :value="item.value" :key="index">{{item.label}}</Option>
            </Select>
          </Col>
          <Col class="search-item">
            <Button class="search-btn" type='primary' @click="doSearch">查询</Button>
          </Col>
          <Col class="search-item">
            <Button class="search-btn" @click="reset">重置</Button>
          </Col>
        </Row>
        <Row type="flex" justify="end" class="search-item-right">
          <Col class="search-item"><Button class="search-btn" type="primary" style="margin-right:8px" @click="skipAdd">添加</Button></Col>
        </Row>
      </Row>
    </div>
    <Table stripe class="table-list" :columns="columns" :data="data" :loading="loading" :height="this.tableHeight">
      <template slot-scope="{ row }" slot="templateType">
         {{ getEnumsName(row.templateType, templateTypeList) }}
      </template>
      <template slot-scope="{ row }" slot="suitableType">
         {{ getEnumsName(row.suitableType, messageActivityList) }}
      </template>
      <template slot-scope="{ row }" slot="content">
         {{row.content}}
      </template>
      <template slot-scope="{ row }" slot="status">
        <span>
          <i-switch v-model="row.status"
                    :disabled="!hasPermission('moms:market:messagetemplateupdate')"
                    @on-change="switch_change(row)">
            <span slot="open">开</span>
            <span slot="close">关</span>
          </i-switch>
        </span>
      </template>
      <template slot-scope="{ row }" slot="action">
        <i class="iconsys iconedit" title="编辑" @click="skipEdit(row)" v-if="hasPermission('moms:market:messagetemplateupdate') && !row.status"></i>
      </template>
    </Table>
    <Row type='flex' justify="end" style='padding: 20px'>
      <Col>
       <Page :total="total"
              :page-size='pageSize'
              :current='pageIndex'
              show-total
              show-sizer
              @on-change='changePageIndex'
              @on-page-size-change='changePageSize' />
      </Col>
    </Row>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import { getMessages, updateMessage } from '@/api/market/message.js'
import enumsMixin from '../enums.js'
export default {
  name: 'market_messagetemplate_list',
  mixins: [enumsMixin],
  data () {
    return {
      couponName: '',
      searchObj: {
        templateType: -1,
        suitableType: -1,
        status: -1
      },
      total: 0,
      pageSize: 10,
      pageIndex: 1,
      loading: false,
      tableHeight: 0,
      data: [],

      columns: [
        {
          title: '消息模板名称',
          key: 'templateName'
        },
        {
          title: '类型',
          slot: 'templateType'
        },
        {
          title: '适用产品',
          slot: 'suitableType'
        },
        {
          title: '消息模板内容',
          slot: 'content'
        },
        {
          title: '状态',
          slot: 'status'
        },
        {
          title: '创建人',
          key: 'creatorName'
        },
        {
          title: '创建时间',
          key: 'createTime'
        }
      ]
    }
  },
  watch: {
    '$route' (newRoute) {
      if (newRoute.name === 'market_messagetemplate_list') {
        this.getData()
      }
    }
  },
  computed: {
    ...mapState({
      merchantId: state => state.user.merchantId,
      userId: state => state.user.userId,
      userName: state => state.user.userName
    })
  },
  mounted () {
    this.getData()
    if (this.hasPermission(['moms:market:messagetemplateupdate'])) {
      this.columns.push({
        title: '操作',
        slot: 'action',
        width: 150
      })
    }
  },
  methods: {
    updateSwitch (param) {
      updateMessage(param.load).then((res) => {
        if (res.status === 200) {
          // this.$set(this.Tabledata[param.valite.index], 'status', param.load.status)
          if (param.load.status) {
            this.$Message.success('开启成功！')
          } else {
            this.$Message.success('关闭成功！')
          }
        } else {
          this.$nextTick(() => {
            this.$set(this.data[param.valite.index], 'status', param.valite.status)
          })
          this.$Message.error(`${res.data.error}`)
        }
      })
    },
    switch_change (row) {
      let param = { load: { id: row.id, status: row.status ? 1 : 0 }, valite: { status: !row.status, index: row._index } }
      this.$set(this.data[row._index], 'status', row.status)
      this.updateSwitch(param)
    },
    getData () {
      this.loading = true
      this.tableHeight = 0
      let params = {
        merchantId: this.merchantId,
        offset: (this.pageIndex - 1) * this.pageSize,
        limit: this.pageSize
      }
      if (this.searchObj.templateType !== -1) {
        params.templateType = this.searchObj.templateType
      }
      if (this.searchObj.suitableType !== -1) {
        params.suitableType = this.searchObj.suitableType
      }
      if (this.searchObj.status !== -1) {
        params.status = this.searchObj.status
      }
      getMessages(params).then(res => {
        this.loading = false
        const result = res.data || {}
        if (result.status === 200) {
          this.data = (result.data || []).map(item => {
            item.status = !!item.status
            return item
          })
          this.total = result.totalCount || 0
          if (this.data.length > 10) {
            this.tableHeight = 520
          }
        } else {
          this.$Message.error(`${result.error}`)
        }
      }).catch(err => {
        this.$Message.error(`${err}`)
        this.loading = false
      })
    },
    search () {
      this.pageIndex = 1
      this.getData()
    },
    doSearch () {
      this.search()
    },
    reset () {
      this.searchObj = {
        status: -1,
        templateType: -1
      }
      this.search()
    },
    changePageIndex (page) {
      this.pageIndex = page
      this.getData()
    },
    changePageSize (size) {
      this.pageSize = size
      this.search()
    },
    skipAdd () {
      this.$router.push({ name: 'market_messagetemplate_create' })
    },
    skipEdit (row) {
      this.$router.push({ name: 'market_messagetemplate_edit', params: { id: row.id } })
    }
  }
}
</script>
